import { useEffect, useState } from 'react';
import { Spin, Space, Button, Drawer, Modal, message, Checkbox } from 'antd';
import { useTablePipeline, features } from 'ali-react-table';
import { connect } from 'umi';

import { TRDefault, TRMessage } from '#/components';
import { UploadOutlined, FileTextOutlined, PlusCircleOutlined } from '#/utils/antdIcons';

import { PageLoading } from '@/components';
import { useTRState, TjTable } from '@/pages/ETrade/components';

import MyDrawer from './components/MyDrawer';
import HistoryShot from './components/HistoryShot';
import DrawerContent from './components/DrawerContent';
import { HttpCode } from '#/utils/contacts.js';

import { default as HeadForm } from './form';
import {
  statementInfoList,
  delElectricityDetailList,
  addElectricityDetailList,
  editElectricityDetailList,
  exportList,
} from './services';
import { getColumns } from './helper';
import moment from 'moment';
import styles from './index.less';
import { useRequestPowerAfterInit } from '@/hooks/useRequestPowerAfterInit';

const { confirm } = Modal;

const ElectricSortManage = (props) => {
  /** data */
  const exportKey = 'NewFreeSettlementDetails';
  const { menuCode, buttonPermissions } = props;
  const [state, setState] = useTRState({
    canExport: buttonPermissions.some((item) => item.menuCode === exportKey),
    canImport: buttonPermissions.some((item) => item.menuCode === exportKey),

    // 初始化三件套
    spinning: false,
    error: '',
    power: [],
    // 表单
    formValues: {},
    selectedRowKeys: [],
    // 数据
    loading: false,
    tableData: [],
  });
  const [visible, setVisible] = useState(false);
  const [editValues, setEditValues] = useState();
  const [btnLoading, setBtnLoading] = useState(false);
  const [refresh, setRefresh] = useState();
  const { initLoading, province } = useRequestPowerAfterInit(
    `/power/dataPower/common/${menuCode}/t_station`,
    (parmas) => {},
    {
      convertResult: '1',
      matchFirst: 0,
    },
  );

  /** methods */

  const _onChangeForm = async (values) => {
    setState({ formValues: values, loading: true });
    const res = await statementInfoList(values);
    let tableData = [];

    if (res.statusCode === HttpCode.SUCCESS) {
      tableData = [...res.data];
    } else {
      message.warning(res.message);
    }

    setState({
      tableData,
      selectedRowKeys: [],
      loading: false,
    });
  };

  const showHistory = async () => {
    const result = await MyDrawer.show({
      title: '操作日志',
      iconType: 1,
      width: 612,
      MyComponent: (props) => <HistoryShot formValues={state.formValues} {...props} />,
    });
    if (result?.index === 1) {
    }
    MyDrawer.dismiss();
  };

  const edit = (record) => {
    const newData = {
      ...record,
    };
    setEditValues(newData);
    setVisible(true);
  };

  const del = (data) => {
    confirm({
      title: '确定删除此行数据吗？',
      onOk: () => {
        delElectricityDetailList(data.id, state.formValues?.marketId).then((res) => {
          if (res && res.statusCode && res.statusCode === '1000') {
            message.success('删除成功');
            setRefresh(moment().valueOf());
          } else {
            message.error('系统异常');
          }
        });
      },
    });
  };

  const add = () => {
    setVisible(true);
  };

  const submitData = (data) => {
    let fn = () => addElectricityDetailList(data);
    if (editValues) {
      const newData = { ...editValues, ...data };
      fn = () => editElectricityDetailList(newData);
    }
    setBtnLoading(true);
    fn()
      .then((res) => {
        if (res) {
          if (res.statusCode && res.statusCode === '1000') {
            message.success(editValues ? '修改成功' : '新增成功');
            setEditValues(undefined);
            setVisible(false);
            setRefresh(moment().valueOf());
          } else {
            message.error(
              editValues ? `修改失败：${res.data.join(',')}` : `新增失败：${res.data.join(',')}`,
            );
          }
        } else {
          message.error('系统异常');
        }
      })
      .finally(() => {
        setBtnLoading(false);
      });
  };

  // 关闭Drawer
  const onClose = () => {
    setVisible(false);
    setEditValues(undefined);
  };

  const handleMultiSelectChange = (nextValue) => {
    setState({ selectedRowKeys: nextValue });
  };

  // 导出
  const _onExport = () => {
    if (!state.canExport) return TRMessage.info('请联系管理员获取相关权限');
    exportList(state.selectedRowKeys, state.formValues?.marketId)
      .then((response) => {
        if (response) {
          const url = window.URL.createObjectURL(new Blob([response]));
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', `电费分类数据_${new Date().toLocaleString()}.xlsx`);
          document.body.appendChild(link);
          link.click();
          link.remove();
        } else {
          TRMessage.error('数据导出失败！');
        }
      })
      .catch((error) => {
        TRMessage.error('数据导出失败！');
      });
  };

  const pipeline = useTablePipeline({
    components: { Checkbox },
  })
    .input({ columns: getColumns({ edit, del }), dataSource: state.tableData })
    .primaryKey('id')
    .use(
      features.multiSelect({
        value: state.selectedRowKeys,
        highlightRowWhenSelected: true,
        checkboxPlacement: 'start',
        checkboxColumn: { lock: true },
        clickArea: 'cell',
        onChange: handleMultiSelectChange,
      }),
    );

  const _renderTable = () => {
    if (state.loading) return null;
    if (!state.tableData?.length) return <TRDefault type="empty" />;
    return <TjTable useVirtual="auto" {...pipeline.getProps()} />;
  };

  if (initLoading) return <PageLoading />;
  if (state.error) return <TRDefault type="error" message={state.error} />;
  if (!province.length) return <TRDefault type="lock" />;
  return (
    <Spin spinning={state.loading}>
      <div className={styles.content}>
        <div className={styles.head}>
          <HeadForm power={province} onChange={_onChangeForm} refresh={refresh} />
          <Space size={16} wrap>
            <Button
              disabled={!state.tableData?.length}
              style={{ padding: 0 }}
              type="link"
              icon={<FileTextOutlined />}
              onClick={showHistory}
            >
              操作日志
            </Button>
            <Button
              disabled={!state.tableData?.length}
              style={{ padding: 0 }}
              type="link"
              icon={<UploadOutlined />}
              onClick={_onExport}
            >
              导出
            </Button>
          </Space>
        </div>
        <div className={styles.main}>
          <div className={styles.box}>
            <div className={styles.flexcolumn}>
              <div className={styles.title}>
                电费分类管理
                <Button
                  style={{ width: 98, height: 32 }}
                  type="link"
                  icon={<PlusCircleOutlined />}
                  onClick={add}
                >
                  新增
                </Button>
              </div>
              <div className={styles.table}>{_renderTable()}</div>
            </div>
          </div>
        </div>
        <Drawer
          title={editValues ? '编辑' : '新增'}
          placement="right"
          onClose={onClose}
          visible={visible}
          width="1164px"
          destroyOnClose
        >
          <DrawerContent
            submit={submitData}
            values={editValues}
            loading={btnLoading}
            optionsData={{
              marketingUnit: province,
            }}
            marketId={state.formValues.marketId}
          />
        </Drawer>
      </div>
    </Spin>
  );
};

export default connect(({ global }) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(ElectricSortManage);
